#include "choosedittasks.h"
#include "ui_choosedittasks.h"
#include <QSqlRelationalDelegate>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QMessageBox>
#include <QQueue>
#include <QDebug>

ChoosEditTasks::ChoosEditTasks(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ChoosEditTasks)
{
    ui->setupUi(this);
    smodel = new QSqlRelationalTableModel(this);
    smodel->setTable("chooser");
    smodel->setRelation(1, QSqlRelation("chooser_themes", "tid", "teng"));
    smodel->setSort(1, Qt::AscendingOrder);
    smodel->select();
    smodel->setHeaderData(1, Qt::Horizontal, tr("Theme name"));
    smodel->setHeaderData(2, Qt::Horizontal, tr("Correct?"));
    smodel->setHeaderData(3, Qt::Horizontal, tr("True answers"));
    smodel->setHeaderData(4, Qt::Horizontal, tr("Question or challange"));
    smodel->setHeaderData(5, Qt::Horizontal, tr("Answer 1"));
    smodel->setHeaderData(6, Qt::Horizontal, tr("Answer 2"));
    smodel->setHeaderData(7, Qt::Horizontal, tr("Answer 3"));
    smodel->setHeaderData(8, Qt::Horizontal, tr("Answer 4"));
    smodel->setHeaderData(9, Qt::Horizontal, tr("Answer 5"));
    smodel->setHeaderData(10, Qt::Horizontal, tr("Answer 6"));
    ui->tableView_Tasks->setModel(smodel);
    ui->tableView_Tasks->setItemDelegate(new QSqlRelationalDelegate(this));
    ui->tableView_Tasks->hideColumn(0);
    ui->tableView_Tasks->hideColumn(2);
    ui->tableView_Tasks->hideColumn(3);
    showAnswersInList(false);
    ui->tableView_Tasks->horizontalHeader()->setResizeMode(1, QHeaderView::ResizeToContents);
    ui->tableView_Tasks->horizontalHeader()->setResizeMode(2, QHeaderView::ResizeToContents);
    ui->tableView_Tasks->horizontalHeader()->setResizeMode(3, QHeaderView::ResizeToContents);
    ui->tableView_Tasks->horizontalHeader()->setResizeMode(4, QHeaderView::ResizeToContents);
    ui->tableView_Tasks->horizontalHeader()->setResizeMode(5, QHeaderView::ResizeToContents);
    ui->tableView_Tasks->horizontalHeader()->setResizeMode(6, QHeaderView::ResizeToContents);
    ui->tableView_Tasks->horizontalHeader()->setResizeMode(7, QHeaderView::ResizeToContents);
    ui->tableView_Tasks->horizontalHeader()->setResizeMode(8, QHeaderView::ResizeToContents);
    ui->tableView_Tasks->horizontalHeader()->setResizeMode(9, QHeaderView::ResizeToContents);
    ui->tableView_Tasks->horizontalHeader()->setResizeMode(10, QHeaderView::ResizeToContents);
    QRegExp rx("^(?!\\s)((?!\\*)(?!\\s\\s).)*$");
    tasksRxV = new QRegExpValidator(rx, this);
    ui->lineEdit_NewQuestion->setValidator(tasksRxV);
    ui->lineEdit_NewAnswer1->setValidator(tasksRxV);
    ui->lineEdit_NewAnswer2->setValidator(tasksRxV);
    ui->lineEdit_NewAnswer3->setValidator(tasksRxV);
    ui->lineEdit_NewAnswer4->setValidator(tasksRxV);
    ui->lineEdit_NewAnswer5->setValidator(tasksRxV);
    ui->lineEdit_NewAnswer6->setValidator(tasksRxV);
    themeSelectorsFill();
}

ChoosEditTasks::~ChoosEditTasks()
{
    delete smodel;
    delete tasksRxV;
    delete ui;
}

void ChoosEditTasks::themeSelectorsFill()
{
    ui->comboBox_SelectTheme->addItem(tr("*All*"), 0);
    QSqlQuery query("SELECT * FROM chooser_themes ORDER BY teng");
    while (query.next()) {
        int idvalue = query.value(0).toInt();
        QString stringvalue(query.value(1).toString());
        stringvalue.append(" | " + query.value(2).toString());
        ui->comboBox_NewTheme->addItem(stringvalue, idvalue);
        ui->comboBox_SelectTheme->addItem(stringvalue, idvalue);
    }
}

void ChoosEditTasks::fetchAllDataFromDB()
{
    while (smodel->canFetchMore())
        smodel->fetchMore();
}

void ChoosEditTasks::searchThisRow(int id)
{
    for (int row = 0; row < smodel->rowCount(); ++row) {
        QSqlRecord record = smodel->record(row);
        if (record.value("id").toInt() == id) {
            ui->tableView_Tasks->selectRow(row);
            break;
        }
    }
}

void ChoosEditTasks::on_comboBox_SelectTheme_currentIndexChanged(int index)
{
    int itemdata = ui->comboBox_SelectTheme->itemData(index).toInt();
    if (itemdata)
        smodel->setFilter("chooser.tid=" + QString::number(itemdata));
    else
        smodel->setFilter("");
    smodel->select();
    fetchAllDataFromDB();
    ui->comboBox_NewTheme->setCurrentIndex((index == 0) ? 0 : index - 1);
}

void ChoosEditTasks::on_pushButton_DeleteSelected_clicked()
{
    QItemSelectionModel *selectionModel = ui->tableView_Tasks->selectionModel();
    QModelIndexList indexes = selectionModel->selectedRows();
    int selnr = indexes.count();
    if (!selnr) {
        QMessageBox::information(this, tr("No row selected"), tr("Not selected a row either."));
        return;
    }
    bool yesToAll = false;
    QMessageBox::StandardButtons questionButtons;
    if (selnr > 1)
        questionButtons = QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::No | QMessageBox::NoToAll;
    else
        questionButtons = QMessageBox::Yes | QMessageBox::No;
    for (int i = 0; i < selnr; ++i) {
        int row = indexes.at(i).row();
        int id = smodel->record(row).value(0).toInt();
        QString sentence = smodel->record(row).value(4).toString();
        int answer = 0;
        if (!yesToAll) {
            QString message(tr("Delete the task:<br><b>"));
            message.append(sentence);
            message.append(tr("</b>?"));
            answer = QMessageBox::question(this, tr("Are you sure?"), message, questionButtons, QMessageBox::No);
        }
        if (answer == QMessageBox::YesToAll)
            yesToAll = true;
        if (answer == QMessageBox::NoToAll)
            break;
        if (yesToAll || answer == QMessageBox::Yes) {
            QSqlQuery delquery;
            delquery.prepare("DELETE FROM chooser WHERE id=:id");
            delquery.bindValue(":id", id);
            delquery.exec();
        }
    }
    smodel->select();
    fetchAllDataFromDB();
}

void ChoosEditTasks::on_pushButton_SubmitNew_clicked()
{
    this->setCursor(Qt::WaitCursor);
    int index = ui->comboBox_NewTheme->currentIndex();
    if (index < 0) {
        QMessageBox::information(this, tr("No themes set."), tr("No themes defined, please select or add least one theme first from the themes editor!"));
        return;
    }
    int tid = ui->comboBox_NewTheme->itemData(index).toInt();
    int taskType = 0;
    if (ui->radioButton_NewIsCorrect->isChecked())
        taskType = 1;
    QString correctAnswerNumbers;
    if (ui->checkBox_NewAns1T->isChecked())
        correctAnswerNumbers = "1";
    if (ui->checkBox_NewAns2T->isChecked())
        correctAnswerNumbers.append("2");
    if (ui->checkBox_NewAns3T->isChecked())
        correctAnswerNumbers.append("3");
    if (ui->checkBox_NewAns4T->isChecked())
        correctAnswerNumbers.append("4");
    if (ui->checkBox_NewAns5T->isChecked())
        correctAnswerNumbers.append("5");
    if (ui->checkBox_NewAns6T->isChecked())
        correctAnswerNumbers.append("6");
    if (correctAnswerNumbers.isEmpty()) {
        QMessageBox::information(this, tr("Not set correct answer"), tr("Not set a good answer, please click at least one checkbox!"));
        return;
    }
    QSqlQuery query;
    int id = 0;
    if (tModifyMode) {
        id = tModifyID;
        query.prepare("UPDATE chooser set tid=:tid, type=:type, correct=:corr, question=:quest, answer1=:ans1, answer2=:ans2, answer3=:ans3, answer4=:ans4, answer5=:ans5, answer6=:ans6 "
                      "WHERE id=:id");
        query.bindValue(":id", id);
    }
    else {
        query.prepare("INSERT INTO chooser (tid, type, correct, question, answer1, answer2, answer3, answer4, answer5, answer6)"
                      " VALUES (:tid, :type, :corr, :quest, :ans1, :ans2, :ans3, :ans4, :ans5, :ans6)");
    }
    query.bindValue(":tid", tid);
    query.bindValue(":type", taskType);
    query.bindValue(":corr", correctAnswerNumbers);
    query.bindValue(":quest", ui->lineEdit_NewQuestion->text().trimmed());
    query.bindValue(":ans1", ui->lineEdit_NewAnswer1->text().trimmed());
    query.bindValue(":ans2", ui->lineEdit_NewAnswer2->text().trimmed());
    query.bindValue(":ans3", ui->lineEdit_NewAnswer3->text().trimmed());
    query.bindValue(":ans4", ui->lineEdit_NewAnswer4->text().trimmed());
    query.bindValue(":ans5", ui->lineEdit_NewAnswer5->text().trimmed());
    query.bindValue(":ans6", ui->lineEdit_NewAnswer6->text().trimmed());
    query.exec();
    if (tModifyMode) {
        tModifyMode = false;
        ui->label_ModifiedNr->setText("#");
        ui->tableView_Tasks->setFocus();
    }
    else {
        id = query.lastInsertId().toInt();
        ui->lineEdit_NewQuestion->setFocus();
    }
    clearNewTaskForm();
    smodel->select();
    searchThisRow(id);
    this->setCursor(Qt::ArrowCursor);
}

void ChoosEditTasks::clearNewTaskForm()
{
    ui->lineEdit_NewQuestion->clear();
    ui->lineEdit_NewAnswer1->clear();
    ui->lineEdit_NewAnswer2->clear();
    ui->lineEdit_NewAnswer3->clear();
    ui->lineEdit_NewAnswer4->clear();
    ui->lineEdit_NewAnswer5->clear();
    ui->lineEdit_NewAnswer6->clear();
    ui->checkBox_NewAns1T->setChecked(false);
    ui->checkBox_NewAns2T->setChecked(false);
    ui->checkBox_NewAns3T->setChecked(false);
    ui->checkBox_NewAns4T->setChecked(false);
    ui->checkBox_NewAns5T->setChecked(false);
    ui->checkBox_NewAns6T->setChecked(false);
    ui->label_ModifiedNr->setText("#");
    ui->radioButton_NewIsCorrect->setChecked(true);
    ui->comboBox_NewTheme->setCurrentIndex(-1);
}

void ChoosEditTasks::showAnswersInList(bool show)
{
    if (show) {
        ui->tableView_Tasks->showColumn(5);
        ui->tableView_Tasks->showColumn(6);
        ui->tableView_Tasks->showColumn(7);
        ui->tableView_Tasks->showColumn(8);
        ui->tableView_Tasks->showColumn(9);
        ui->tableView_Tasks->showColumn(10);
    }
    else {
        ui->tableView_Tasks->hideColumn(5);
        ui->tableView_Tasks->hideColumn(6);
        ui->tableView_Tasks->hideColumn(7);
        ui->tableView_Tasks->hideColumn(8);
        ui->tableView_Tasks->hideColumn(9);
        ui->tableView_Tasks->hideColumn(10);
    }
}

void ChoosEditTasks::on_pushButton_clicked()
{
    tModifyMode = false;
    clearNewTaskForm();
}

void ChoosEditTasks::on_tableView_Tasks_doubleClicked(const QModelIndex &index)
{
    clearNewTaskForm();
    int rowindex = index.row();
    int colindex = index.column();
    tModifyMode = true;
    tModifyID = smodel->record(rowindex).value(0).toInt();
    ui->label_ModifiedNr->setText("#" + QString::number(rowindex + 1));
    int themeindex = 0;
    themeindex = ui->comboBox_NewTheme->findText(smodel->record(rowindex).value(1).toString(), Qt::MatchStartsWith);
    ui->comboBox_NewTheme->setCurrentIndex(themeindex);
    if (smodel->record(rowindex).value(2).toInt())
        ui->radioButton_NewIsCorrect->setChecked(true);
    else
        ui->radioButton_NewIsIncorrect->setChecked(true);
    QString correctstring(smodel->record(rowindex).value(3).toString());
    int correctstrlen = correctstring.length();
    for (int i = 0; i < correctstrlen; ++i) {
        int cnr = correctstring.at(i).digitValue();
        switch (cnr) {
        case 1:
            ui->checkBox_NewAns1T->setChecked(true);
            break;
        case 2:
            ui->checkBox_NewAns2T->setChecked(true);
            break;
        case 3:
            ui->checkBox_NewAns3T->setChecked(true);
            break;
        case 4:
            ui->checkBox_NewAns4T->setChecked(true);
            break;
        case 5:
            ui->checkBox_NewAns5T->setChecked(true);
            break;
        case 6:
            ui->checkBox_NewAns6T->setChecked(true);
            break;
        }
    }
    ui->lineEdit_NewQuestion->setText(smodel->record(rowindex).value(4).toString());
    ui->lineEdit_NewAnswer1->setText(smodel->record(rowindex).value(5).toString());
    ui->lineEdit_NewAnswer2->setText(smodel->record(rowindex).value(6).toString());
    ui->lineEdit_NewAnswer3->setText(smodel->record(rowindex).value(7).toString());
    ui->lineEdit_NewAnswer4->setText(smodel->record(rowindex).value(8).toString());
    ui->lineEdit_NewAnswer5->setText(smodel->record(rowindex).value(9).toString());
    ui->lineEdit_NewAnswer6->setText(smodel->record(rowindex).value(10).toString());
    switch (colindex) {
    case 1:
        ui->comboBox_NewTheme->setFocus();
        break;
    case 4:
        ui->lineEdit_NewQuestion->setFocus();
        break;
    case 5:
        ui->lineEdit_NewAnswer1->setFocus();
        break;
    case 6:
        ui->lineEdit_NewAnswer2->setFocus();
        break;
    case 7:
        ui->lineEdit_NewAnswer3->setFocus();
        break;
    case 8:
        ui->lineEdit_NewAnswer4->setFocus();
        break;
    case 9:
        ui->lineEdit_NewAnswer5->setFocus();
        break;
    case 10:
        ui->lineEdit_NewAnswer6->setFocus();
        break;
    }
}
